import os
import sys
from aipyapp import runtime

def package():
    """使用 PyInstaller 打包 GUI 程序为单个 .exe 文件"""
    # 检查并安装 PyInstaller
    if not runtime.install_packages("pyinstaller"):
        print("❌ 安装 PyInstaller 失败，无法打包", file=sys.stderr)
        return
    
    # 打包命令：--onefile 生成单个文件，--windowed 隐藏控制台窗口
    cmd = [
        "pyinstaller",
        "--onefile",          # 单个可执行文件
        "--windowed",         # GUI 程序无控制台窗口
        "--name", "GitPatchEditor",  # 可执行文件名称
        "git_patch_editor_gui.py"    # 要打包的脚本
    ]
    
    try:
        import subprocess
        result = subprocess.run(
            cmd,
            check=True,
            capture_output=True,
            text=True
        )
        print("📦 打包输出:")
        print(result.stdout)
        
        # 检查输出文件
        exe_path = os.path.join("dist", "GitPatchEditor.exe")
        if os.path.exists(exe_path):
            print(f"\n🎉 打包成功！可执行文件位置:")
            print(f"   {os.path.abspath(exe_path)}")
        else:
            print("\n❌ 打包成功但未找到可执行文件", file=sys.stderr)
    except subprocess.CalledProcessError as e:
        print(f"❌ 打包失败: {e.stderr}", file=sys.stderr)
    except Exception as e:
        print(f"❌ 打包异常: {str(e)}", file=sys.stderr)

if __name__ == "__main__":
    package()